package com.example.jsd2205.vx.emos.config.shiro;

import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import org.apache.http.HttpStatus;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.web.filter.authc.AuthenticatingFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Scope;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
/**
 * 过滤器
 * 判断那些请求应该被Shiro处理
 * 判断Token是真过期还是假过期
 * 存储新令牌
 * @author admin闫
 */
@Component
@Scope("prototype")//多例对象非单例
public class OAuth2Filter extends AuthenticatingFilter {//覆盖父类中的一些方法
    /**
     * 引入threadLocalToken媒介类 存储token
     */
    @Autowired
    private ThreadLocalToken threadLocalToken;
    /**
     *引用过期时间
     */
    @Value("${emos.jwt.cache-expire}")//值注入
    private int cacheExpire;
    /**
     *验证令牌使用
     */
    @Autowired
    private JwtUtil jwtUtil;
    /**
     * 引用RedisTemplate方便操作Redis
     */
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 覆盖createToken方法 从请求中获取令牌字符串,封装成token对象
     * @param request
     * @param response
     * @return AuthenticationToken
     * @throws Exception
     */
    @Override
    protected AuthenticationToken createToken(ServletRequest request, ServletResponse response) throws Exception {
        //转换成Http类型的请求
        HttpServletRequest req= (HttpServletRequest) request;
        //获取请求token
        String token=getRequestToken(req);
        if(StrUtil.isBlank(token)){
            return null;
        }
        //封装成token对象
        return new OAuth2Token(token);
    }

    /**
     * 拦截请求,判断请求是否需要被Shiro处理
     * @param request
     * @param response
     * @param mappedValue
     * @return Boolean
     */
    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        HttpServletRequest req= (HttpServletRequest) request;
        //Ajax提交application/json数据的时候,会先发出Option请求
        //这里要方形Option请求,不需要Shiro处理
        if(req.getMethod().equals(RequestMethod.OPTIONS.name())){//判断请求是不是Option类型的
            return true;
        }
        //除了Options请求之外,所有请求都要被Shiro处理
        return false;
    }

    /**
     * 该方法用于处理所有应该被Shiro处理的请求
     * @param request
     * @param response
     * @return Boolean
     * @throws Exception
     */
    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        //先做Http请求类型的转换
        HttpServletRequest req= (HttpServletRequest) request;
        HttpServletResponse resp= (HttpServletResponse) response;
        //设置一些响应头
        resp.setContentType("text/html");//类型
        resp.setCharacterEncoding("UTF-8");//字符集
        resp.setHeader("Access-Control-Allow-Credentials", "true");//跨域参数,允许跨域
        resp.setHeader("Access-Control-Allow-Origin", req.getHeader("Origin"));
        //清理threadLocalToken中的数据
        threadLocalToken.clear();
        //从请求头中获取Token对象
        String token=getRequestToken(req);
        if(StrUtil.isBlank(token)){
            resp.setStatus(HttpStatus.SC_UNAUTHORIZED);//401
            resp.getWriter().print("无效的令牌");
            return false;
        }
        try{
            jwtUtil.verifierToken(token);//验证令牌
        }catch (TokenExpiredException e){//捕获 TokenExpiredException 代表令牌过期
            if(redisTemplate.hasKey(token)){//查看Redis有没有缓存的令牌数据
                //令牌刷新 假过期
                redisTemplate.delete(token);
                int userId=jwtUtil.getUserId(token);
                token=jwtUtil.createToken(userId);
                redisTemplate.opsForValue().set(token,userId+"",cacheExpire, TimeUnit.DAYS);
                threadLocalToken.setToken(token);
            }
            else{
                //令牌过期 真过期
                resp.setStatus(HttpStatus.SC_UNAUTHORIZED);
                resp.getWriter().print("令牌已过期");
                return false;
            }
        }catch (Exception e){ //捕获异常代表 无效的令牌 令牌字符串内容不对(伪造)
            resp.setStatus(HttpStatus.SC_UNAUTHORIZED);
            resp.getWriter().print("无效的令牌(伪造)");
            return false;
        }
        boolean bool=executeLogin(request,response);//间接调用Realm类
        return bool;
    }

    /**
     * 覆盖判断用户没有登录与登录失败的处理方案
     * @param token
     * @param e
     * @param request
     * @param response
     * @return boolean
     */
    @Override
    protected boolean onLoginFailure(AuthenticationToken token, AuthenticationException e, ServletRequest request, ServletResponse response) {
        HttpServletRequest req= (HttpServletRequest) request;
        HttpServletResponse resp= (HttpServletResponse) response;
        resp.setContentType("text/html");
        resp.setCharacterEncoding("UTF-8");
        resp.setHeader("Access-Control-Allow-Credentials", "true");
        resp.setHeader("Access-Control-Allow-Origin", req.getHeader("Origin"));
        resp.setStatus(HttpStatus.SC_UNAUTHORIZED);//设置状态码401
        try{
            resp.getWriter().print(e.getMessage());//返回认证失败详细的消息
        }catch (Exception exception){

        }

        return false;
    }

    /**
     * 覆盖拦截请求和返回响应的方法
     * @param request
     * @param response
     * @param chain
     * @throws ServletException
     * @throws IOException
     */
    @Override
    public void doFilterInternal(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
//        HttpServletRequest req= (HttpServletRequest) request;
//        HttpServletResponse resp= (HttpServletResponse) response;
//        resp.setContentType("text/html");
//        resp.setCharacterEncoding("UTF-8");
//        resp.setHeader("Access-Control-Allow-Credentials", "true");
//        resp.setHeader("Access-Control-Allow-Origin", req.getHeader("Origin"));
        super.doFilterInternal(request, response, chain);

    }

    /**
     * 从请求头中提取token字符串
     * @param request
     * @return String token
     */
    private String getRequestToken(HttpServletRequest request){
        String token=request.getHeader("token");
        if(StrUtil.isBlank(token)){
            token=request.getParameter("token");
        }
        return token;
    }
}